// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  let orderid = event.outTradeNo;     // 商户订单号
  let openid = event.subOpenid;       // 用户openid
  let timeEnd = event.timeEnd;        // timeEnd
  let subMchId = event.subMchId;      // 返回子商户号
  let returnCode = event.returnCode;  // 返回状态码
  let resultCode = event.resultCode;
  // 注意：两者都为SUCCESS，支付才算正真成功
  if (returnCode == 'SUCCESS' && resultCode == 'SUCCESS') {
    const db = cloud.database()
    // 更新云数据库数据
    let order = await db.collection("userOrder").where({
      openid: openid,
      orderid: orderid,
    }).get()
    console.log(order.data[0].status)
    let thisStatus = order.data[0].status
    if (thisStatus == 1) {
      return {
        errcode: 0,
        errmsg: 'SUCCESS',
        status: '1'
      }
    } else if (thisStatus == 0) {
      // 更新状态  根据当前购买者的openid 跟订单号查询是否有数据 并更新是否已经支付的状态
      let updataO = await db.collection('userOrder').where({
        openid: openid,
        orderid: orderid,
      }).update({
        data: {
          status: 1,
          timeEnd: timeEnd,
          subMchId: subMchId
        }
      })
      console.log(updataO)
      // 如果更新成功
      if (updataO.stats.updated == 1) {
        return {
          errcode: 0,
          errmsg: 'SUCCESS',
          status: '2.1'
        }
      } else {
        // 向数据库添加错误处理订单
        let addFail = await db.collection('failOrder').add({
          data: {
            openid: openid,
            orderid: orderid,
            remark: 'status订单支付状态更新失败，添加一条容错'
          }
        });
        console.log(addFail)

        return {
          errcode: 1,
          errmsg: 'FAIL',
          status: '2.2'
        }
      }
    } else {
      console.log("nononononono")
      console.log('没查到')
      return {
        errcode: 1,
        errmsg: 'FAIL',
        status: '3'
      }
    }
  } else {
    // 记录错误信息
    conslog.log('支付出错：', event)
    return {
      errcode: 1,
      errmsg: 'FAIL',
      status: '4'
    }
  }
}